import * as xlsx from 'xlsx'
import { saveAs } from 'file-saver'

export const exportToExcel = (data: Array<any>, fileName: string) => {
  console.log(data)
  if (!data || data.length === 0) return
  const header = Object.keys(data[0])
  // 创建工作表
  const workSheet = xlsx.utils.json_to_sheet(data, { header })
  // 创建工作簿
  const workBook = xlsx.utils.book_new()
  // 将工作表添加到工作簿中
  xlsx.utils.book_append_sheet(workBook, workSheet, 'sheet1')
  // 将工作簿转成二进制文件
  const buffer = xlsx.write(workBook, { bookType: 'xlsx', type: 'buffer' })
  // 保存和下载
  saveAs(new Blob([buffer], { type: 'application/octet-stream' }), fileName)
}
